// 等待DOM加载完成后再执行
document.addEventListener('DOMContentLoaded', function() {
    // 获取网站目录
    $.ajax({
        url: '/switch_directory/',
        type: 'POST',
        success: function (data) {
            // 确保DOM元素存在
            var select = document.getElementById("runPath");
            if (select) {
                // 清空现有选项
                select.innerHTML = '';
                
                // 循环添加选项
                if (data.dirs && Array.isArray(data.dirs)) {
                    for (var i = 0; i < data.dirs.length; i++) {
                        var option = document.createElement("option");
                        option.value = data.dirs[i];
                        option.innerHTML = data.dirs[i];
                        select.appendChild(option);
                    }
                    // 获取当前目录
                    if (data.runPath) {
                        select.value = data.runPath;
                    }
                }
            } else {
                console.error("Element with ID 'runPath' not found");
            }
        },
        error: function(xhr, status, error) {
            console.error("Failed to load directory data:", error);
        }
    });
});

// 获取下拉框的值
function SetSiteRunPath() {
    var select = document.getElementById("runPath");
    if (select) {
        var runPath = select.value;
        $.ajax({
            url: '/switch_directory/SetSiteRunPath',
            type: 'POST',
            data: {
                'runPath': runPath
            },
            success: function (data) {
                layer.msg(data.msg,{icon: 'success'});
            },
            error: function(xhr, status, error) {
                console.error("Failed to set run path:", error);
                layer.msg('设置失败，请重试',{icon: 'error'});
            }
        });
    } else {
        console.error("Element with ID 'runPath' not found");
    }
}